﻿//*** Guidance generated code ***//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

using Newtonsoft.Json.Converters;

using ProjectBase.Core;

namespace $safeprojectname$
{
    public class ActionSelectFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext context)
        {
            base.OnActionExecuting(context);
            var service = context.ControllerContext.Controller as IEntityService;
            if (service.IsNull())
            {
                return;
            }

            var IsActionHandled = OnFind(service, context);
            if (IsActionHandled)
            {
                return;
            }

            var values = context.ControllerContext.RouteData.Values;
            object actionValue = null;

            if (!values.TryGetValue("action", out actionValue))
            {
                return;
            }

            var action = actionValue.ToString().ToLowerInvariant();
            switch (action)
            {
                case "new":
                    OnNew(service, context);
                    break;
            }
        }

        protected virtual bool OnFind(IEntityService service, HttpActionContext context)
        {
            if (context.ActionArguments.ContainsKey("filter"))
            {
                var filter = context.ActionArguments["filter"] as IFilter<int>;
                if (filter.Is())
                {
                    service.RequestResolver.AllowedProperties = filter.SelectColumns;
                    return true;
                }
            }
            return false;
        }

        protected virtual bool OnNew(IEntityService service, HttpActionContext context)
        {
            var metaData = service.MetaDataProvider.GetMetaData();

            var readAttributes = metaData.Attributes.Where(a => !a.CanEdit);

            foreach (var attribute in readAttributes)
            {
                service.RequestResolver.IgnoredProperties.Add(attribute.Name);
            }

            return false;
        }
    }
}